import deepClone from '@/libs/deepClone'
import {FormInstance} from 'ant-design-vue'
import {PropType} from 'vue'

const CForm = defineComponent({
  props: {
    model: {
      type: Object as PropType<{[key: string]: any}>
    },
    loading: {
      type: Boolean,
      defalut: false
    },
    labelCol: {
      type: Object as PropType<{[key: string]: any}>,
      default: () => {
        return {span: 4}
      }
    },
    wrapperCol: {
      type: Object as PropType<{[key: string]: any}>,
      default: () => {
        return {span: 20}
      }
    },
    footerClass: {
      type: String,
      default: ''
    },
    submitBtnName: {
      type: String,
      default: '查询'
    },
    resetBtnName: {
      type: String,
      default: '重置'
    }
  },
  emits: {
    formSubmit: (formRef: FormInstance | undefined): boolean => true,
    formReset: (): boolean => true,
    'update:model': (formRef: FormInstance): boolean => true
  },
  setup(props, {emit, slots}) {
    const formRef = ref<FormInstance>()
    const formState = ref<any>()

    watch(
      () => props.model,
      n => {
        formState.value = deepClone(props.model)
      }
    )

    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      emit('formSubmit', formRef.value)
    }

    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      emit('formSubmit', formRef.value)
    }

    /**表单 重置按钮 点击 */
    const handle_form_reset = () => {
      viewLeftContent_reset()
      emit('formReset')
    }

    // 清空表单
    const viewLeftContent_reset = () => {
      formRef.value?.resetFields()
      emit('update:model', formState.value)
    }

    onMounted(() => {
      formState.value = deepClone(props.model)
    })
    return () => (
      <a-form
        class='overflow-auto relative'
        v-models={[
          [formRef, 'ref'],
          [formState.value, 'model']
        ]}
        label-col={props.labelCol}
        wrapper-col={props.wrapperCol}
        onFinish={handle_form_finish}
        onFinishFailed={handle_form_finish_failed}
      >
        {slots.default?.()}
      </a-form>
    )
  }
})

export default CForm
